package team.scau.laboratory_repair.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.jpa.impl.JPAQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.scau.laboratory_repair.common.base.BaseService;
import team.scau.laboratory_repair.common.page.MyPage;
import team.scau.laboratory_repair.common.utils.ztree.ZTreeNode;
import team.scau.laboratory_repair.modules.po.Domain;
import team.scau.laboratory_repair.modules.po.QDomain;
import team.scau.laboratory_repair.modules.po.User;
import team.scau.laboratory_repair.modules.repository.DomainRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 30254
 * creadtedate:2018/10/25
 */
@Service
public class DomainService extends BaseService<Domain, DomainRepository> {
    @Autowired
    private UserService userService;

    @Autowired
    private DomainRepository repository;
    private QDomain qDomain = QDomain.domain;

    @Override
    public DomainRepository getRepository() {
        return repository;
    }

    @Override
    public EntityPathBase<Domain> getQBase() {
        return qDomain;
    }

    public Domain listByAreaAndRoom(Long areaId, String room) {
        JPAQuery<Domain> jpaQuery = queryFactory.select(qDomain).from(qDomain).where(qDomain.areaId.eq(areaId))
                .where(qDomain.room.eq(room))
                .where(qDomain.valid.eq(true));
        return jpaQuery.fetchOne();
    }

    public QueryResults<Domain> listOrByExample(Domain domain, MyPage page) {
        JPAQuery<Domain> jpaQuery = queryFactory.select(qDomain).from(qDomain);
        if (domain != null) {
            if (domain.getAreaId() != null) {
                jpaQuery = jpaQuery.where(qDomain.areaId.eq(domain.getAreaId()));
                if (StringUtils.isNotBlank(domain.getRoom())) {
                    jpaQuery = jpaQuery.where(qDomain.room.eq(domain.getRoom()));
                }
            }
        }
        jpaQuery = jpaQuery.where(qDomain.valid.eq(true));
        return jpaQuery.fetchResults();
    }

    public List<ZTreeNode> selectStaffTree(Domain domain) throws Exception {

        List<User> users = userService.listAllStaff();

        List<String> idArray = StringUtils.isBlank(domain.getStaffIds()) ? new ArrayList<>()
                : Arrays.asList(domain.getStaffIds().split(","));
        List<ZTreeNode> tree = new ArrayList<>();
        for (User user : users) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId(user.getId() + "");
            treeNode.setName(user.getUsername());
            if(idArray.contains(user.getId().toString())) {
                treeNode.setChecked(true);
            }
            tree.add(treeNode);
        }
        return tree;
    }
}
